import React, {useState} from 'react';
import {
    Card, Upload, Input, Form, Button,
    message, Space, Tabs, Modal, ModalFuncProps, notification
} from 'antd';
import {InboxOutlined, FileTextOutlined, CheckCircleOutlined} from '@ant-design/icons';
import {RcFile, UploadFile} from 'antd/lib/upload/interface';
import styles from './index.module.css';
import {textApi} from "../../../services/api/text";

const {Dragger} = Upload;
const {TextArea} = Input;
const {TabPane} = Tabs;

interface FormValues {
    title: string;
    content: string;
}

const TextUploadPage: React.FC = () => {
    const [form] = Form.useForm<FormValues>();
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [uploading, setUploading] = useState(false);
    const [uploadType, setUploadType] = useState<'text' | 'file'>('text');
    const [formValues, setFormValues] = useState<FormValues>({
        title: '',
        content: ''
    });

    const handleFormValuesChange = (_: any, allValues: FormValues) => {
        setFormValues(allValues);
    };

    const canUpload = () => {
        if (uploadType === 'text') {
            return !!formValues.title && !!formValues.content;
        }
        return fileList.length > 0;
    };

    // 创建一个显示成功提示框的函数
    // 显示成功通知
    const showSuccessNotification = (response: any) => {
        notification.success({
            message: '上传成功',
            description: (
                <div>
                    <p>{response.message || '文本内容已成功上传！'}</p>
                    <p>上传时间：{new Date().toLocaleString()}</p>
                </div>
            ),
            icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
            duration: 4.5,
            placement: 'topRight',
            onClose: () => {
                // 通知关闭后清空表单
                form.resetFields();
                setFormValues({ title: '', content: '' });
            }
        });
    };


    const handleUpload = async () => {
        try {
            setUploading(true);

            if (uploadType === 'text') {
                const values = await form.validateFields();
                console.log('表单数据:', values);

                try {
                    const response = await textApi.uploadText({
                        title: values.title,
                        content: values.content
                    });

                    console.log('上传响应:', response);

                    // 直接处理 response 对象
                    if (response && response.code === 200) {
                        form.resetFields();
                        setFormValues({title: '', content: ''});
                        console.log("清空表单")
                        Modal.success({
                            title: '上传成功',
                            content: response.message || '文本内容已成功上传！',
                            okText: '确定'
                        });
                        // console.log('准备显示成功提示框');
                        // showSuccessNotification(response);

                    } else {
                        // 处理非 200 状态
                        message.error(response?.message || '上传失败');
                    }
                } catch (apiError: any) {
                    console.error('API调用错误:', apiError);
                    message.error(apiError.message || '上传失败');
                }
            } else {
                // 文件上传部分保持不变...
                if (fileList.length === 0) {
                    message.error('请选择要上传的文件');
                    return;
                }

                for (const file of fileList) {
                    if (!file.originFileObj) {
                        message.error(`文件 ${file.name} 无效`);
                        continue;
                    }

                    const response = await textApi.uploadFile(file.originFileObj as RcFile);
                    if (response.code !== 200) {
                        throw new Error(`文件 ${file.name} 上传失败：${response.message}`);
                    }
                }

                setFileList([]);
                Modal.success({
                    title: '上传成功',
                    content: `${fileList.length}个文件已成功上传！`,
                    okText: '确定'
                });

            }
        } catch (error: any) {
            console.error('上传错误:', error);
            message.error('上传失败：' + (error.message || '未知错误'));
        } finally {
            setUploading(false);
        }
    };

    const handleReset = () => {
        setFileList([]);
        form.resetFields();
        setFormValues({title: '', content: ''});
        message.info('已清空所有内容');
    };

    const uploadProps = {
        multiple: true,
        accept: '.txt,.doc,.docx,.pdf',
        fileList,
        beforeUpload: (file: RcFile) => {
            const isValidType = [
                'text/plain',
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'application/pdf'
            ].includes(file.type);

            if (!isValidType) {
                message.error('只支持 .txt, .doc, .docx, .pdf 格式的文件！');
                return Upload.LIST_IGNORE;
            }

            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                message.error('文件必须小于10MB！');
                return Upload.LIST_IGNORE;
            }

            // 创建UploadFile对象
            const uploadFile: UploadFile = {
                uid: `-${Date.now()}-${Math.random().toString(36).substr(2)}`,
                name: file.name,
                size: file.size,
                type: file.type,
                lastModified: file.lastModified,
                lastModifiedDate: new Date(file.lastModified),
                percent: 0,
                originFileObj: file
            };

            setFileList(prev => [...prev, uploadFile]);
            return false;
        },
        onRemove: (file: UploadFile) => {
            setFileList(prev => prev.filter(item => item.uid !== file.uid));
            return true;
        }
    };

    return (
        <div className={styles.container}>
            <Card title="文本上传" className={styles.uploadCard}>
                <Tabs
                    activeKey={uploadType}
                    onChange={(key: string) => {
                        setUploadType(key as 'text' | 'file');
                        handleReset();
                    }}
                >
                    <TabPane tab="直接输入文本" key="text">
                        <Form
                            form={form}
                            layout="vertical"
                            onValuesChange={handleFormValuesChange}
                        >
                            <Form.Item
                                label="文本标题"
                                name="title"
                                rules={[{required: true, message: '请输入文本标题'}]}
                            >
                                <Input placeholder="请输入文本标题"/>
                            </Form.Item>

                            <Form.Item
                                label="文本内容"
                                name="content"
                                rules={[{required: true, message: '请输入文本内容'}]}
                            >
                                <TextArea
                                    rows={10}
                                    placeholder="请输入要上传的文本内容"
                                />
                            </Form.Item>
                        </Form>
                    </TabPane>

                    <TabPane tab="上传文件" key="file">
                        <Dragger {...uploadProps}>
                            <p className="ant-upload-drag-icon">
                                <InboxOutlined/>
                            </p>
                            <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
                            <p className="ant-upload-hint">
                                支持 .txt, .doc, .docx, .pdf 格式文件，单个文件大小不超过10MB
                            </p>
                        </Dragger>

                        {fileList.length > 0 && (
                            <div className={styles.uploadList}>
                                <h4 className={styles.uploadListTitle}>待上传文件：</h4>
                                {fileList.map((file, index) => (
                                    <div key={index} className={styles.uploadListItem}>
                                        <FileTextOutlined/> {file.name}
                                    </div>
                                ))}
                            </div>
                        )}
                    </TabPane>
                </Tabs>

                <div className={styles.uploadActions}>
                    <Space>
                        <Button
                            type="primary"
                            onClick={handleUpload}
                            disabled={!canUpload() || uploading}
                            loading={uploading}
                        >
                            {uploading ? '上传中...' : '开始上传'}
                        </Button>
                        <Button onClick={handleReset}>
                            重置
                        </Button>
                    </Space>
                </div>
            </Card>
        </div>
    );
};

export default TextUploadPage;
